const config = require('../../config/config.permission');

module.exports = options => {
  return async function permission(ctx, next) {
    if (config.enable && ctx.user && !config.whiteList.includes(ctx.user.authority)) {
      const userPermissions = await ctx.app.mysql.select('user_permission', {
        user_id: ctx.user.id
      });
      for (let i = 0; i < userPermissions.length; i++) {
        let permission = await ctx.app.mysql.get('permission', {
          id: userPermissions[i].permission_id
        });
        if (permission && permission.url === ctx.path) {
          return await next();
        }
      }
      return ctx.fail('没有权限', 1111);
    }
    await next();
  }

}